from subprocess import Popen,PIPE
from multiprocessing import Pool
import sys
from copy import copy

file=open("./ipList.txt","w")

def ping(ip):
  res=Popen("ping {}".format(ip),stdout=PIPE,shell=True)
  if "TTL" in str(res.stdout.read()):
    print("{} is exist".format(ip))
    return ip
  else:
    pass
 
def getArgs():
  args=sys.argv
  args.pop(0)
  newArg={}
  i=1
  while i<len(args):
    newArg[args[i-1]]=args[i]
    i+=2
  return newArg

def getsubnetMask(subnetMask=""):
  subnetMaskList=[]
  subnetMask=subnetMask.split(".")
  for n in subnetMask:
    degree=0
    if int(n)==0:
      subnetMaskList.append(0)
      continue
    num=0
    for i in range(1,9):
      num+=2**(8-i)
      degree+=1
      if int(n)==num:
        subnetMaskList.append(degree)
        break
  return subnetMaskList

if __name__=="__main__":
  args=getArgs()
  host=args.get("-h")
  s=args.get("-s") if args.get("-s") else "255.255.255.0"
  subnetMask=getsubnetMask(s)
  ipList=[]
  ips=""
  ipsIndex=0
  supIpList=[]
  pool=args.get("-p") if args.get("-p") else 40
  p=Pool(pool)
  for subnetMask1 in subnetMask:
    if subnetMask1==8:
      ips="{}{}".format(ips,str(host.split(".")[ipsIndex])+".")
      ipsIndex+=1
      ipList=[ips]
      continue
    supIpList=copy(ipList)
    ipList=[]
    for supIp in supIpList:
      for ip in range(0,2**(8-subnetMask1)):
        if ipsIndex==3:
          ppp="{}{}".format(supIp,str(int(host.split(".")[ipsIndex])+ip))
          ipList.append(ppp)
        else:
          ppp="{}{}".format(supIp,str(int(host.split(".")[ipsIndex])+ip)+".")
          ipList.append(ppp)
    ipsIndex+=1
  processList=[]
  resultList=[]
  for ip in ipList:
    resultList.append(p.apply_async(ping,args=(ip,)))
  p.close()
  p.join()
  ips=""
  ipLength=0
  for res in resultList:
    if res.get()!=None:
     ips="{}{}\n".format(ips,res.get()) 
     ipLength+=1
  file.write(ips)
  print("该网段共存在{}个ip".format(ipLength))